package com.ruoyi.common.utils.file;

import com.ruoyi.common.pojo.SheetData;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * @author qbf
 */
public class ExcelExporter {

    /**
     * 将List<List<String>>数据导出为Excel文件。
     * @param dataList 包含表头和数据的列表
     * @param out 输出流
     * @throws IOException 如果文件操作失败时抛出
     */
    public static void exportToExcel(List<List<String>> dataList, OutputStream out) throws IOException {

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        int rowNum = 0;
        for (List<String> rowData : dataList) {
            Row row = sheet.createRow(rowNum++);
            int colNum = 0;
            for (String cellData : rowData) {
                Cell cell = row.createCell(colNum++);
                cell.setCellValue(cellData);
            }
        }

        // 写入文件
        workbook.write(out);
        workbook.close();
    }

    /**
     * 将List<List<String>>数据导出为Excel文件。
     * @param sheetDataList sheet页数据
     * @param out 输出流
     * @throws IOException 如果文件操作失败时抛出
     */
    public static void exportToMultiSheetExcel(List<SheetData> sheetDataList, OutputStream out) throws IOException {

        Workbook workbook = new XSSFWorkbook();
        for(SheetData sheetData: sheetDataList){
            Sheet sheet = workbook.createSheet(sheetData.getName());

            int rowNum = 0;
            for (List<String> rowData : sheetData.getData()) {
                Row row = sheet.createRow(rowNum++);
                int colNum = 0;
                for (String cellData : rowData) {
                    Cell cell = row.createCell(colNum++);
                    cell.setCellValue(cellData);
                }
            }

        }


        // 写入文件
        workbook.write(out);
        workbook.close();
    }
}